package com.emath.activities;

import java.util.Date;
import java.util.Random;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.emath.EnterUsername;
import com.emath.HelpDialog;
import com.lnl.R;
import com.emath.objects.Card;
import com.emath.objects.Username;
import com.emath.shared.Globals;
import com.emath.shared.RestClient;


public class CardShop extends Activity {
	/** Called when the activity is first created. */
	LinearLayout collection_table, library_table;
	HorizontalScrollView scrollView;
	int numOfCards = 0, cardFocus = 0;
	ImageView display, separator;
	TextView cardName, type, cost1, mind1, mind2, mind3, charm1, charm2,
			charm3, strength1, strength2, strength3, levelUp, special,
			specialEffect, cost, wiki, uniqueID, playDeck, tokens;
	MediaPlayer cardSound = new MediaPlayer();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cardshop);
		cardSound = MediaPlayer.create(CardShop.this, R.raw.soundchoice);
		// Setting Fonts
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/Capture_it.ttf");

		Button setFocus = (Button) findViewById(R.id.buyCardBtn);
		setFocus.setTypeface(tf);

		TextView tempTV;
		tempTV = (TextView) findViewById(R.id.typeTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.mindTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.charmTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.strengthTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.costTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.specialTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.levelUpTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.wikiTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.collectionTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.libraryTitle);
		tempTV.setTypeface(tf);
		tempTV = (TextView) findViewById(R.id.numOfTokensTitle);
		tempTV.setTypeface(tf);

		// This while loop simply ensures that the collectionObj is done
		// populating before proceeding with the display of the CardShop
		// contents.
		while (!Globals.collectionObj.getObjectState().equals("free")) {
			try {// A sleep thread is used to cut down on processor time used
					// here
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		collection_table = (LinearLayout) findViewById(R.id.layoutForEachCard);
		library_table = (LinearLayout) findViewById(R.id.layoutForLibrary);
		display = (ImageView) findViewById(R.id.selectedCardImage);
		display.setPadding(3, 3, 3, 3);
		display.setAdjustViewBounds(true);
		display.setScaleType(ScaleType.CENTER_INSIDE);
		cardName = (TextView) findViewById(R.id.cardNameData);
		type = (TextView) findViewById(R.id.typeData);
		mind1 = (TextView) findViewById(R.id.mindData);
		charm1 = (TextView) findViewById(R.id.charmData);
		strength1 = (TextView) findViewById(R.id.strengthData);
		cost1 = (TextView) findViewById(R.id.costData);
		special = (TextView) findViewById(R.id.specialData);
		levelUp = (TextView) findViewById(R.id.levelUpData);
		tokens = (TextView) findViewById(R.id.numOfTokensData);
		uniqueID = (TextView) findViewById(R.id.uniqueIdData);
		wiki = (TextView) findViewById(R.id.wikiData);

		setFocus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MediaPlayer buttonSound = new MediaPlayer();
				buttonSound = MediaPlayer.create(CardShop.this,
						R.raw.button_click);
				buttonSound.start();
				if (Globals.user.getTokens() > 0) {

					new Purchasing().execute(getApplicationContext());
				} else {
					Toast.makeText(getApplicationContext(),
							"You have no tokens.", Toast.LENGTH_LONG).show();
				}

			}
		});
		fillCollectionTable();
		fillLibraryTable();
	}

	@Override
	protected void onResume() {
		// Refresh
		super.onResume();
		findViewById(android.R.id.content).invalidate();
	}

	void fillCollectionTable() {
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		layoutParams.setMargins(5, 0, 5, 0);
		if (collection_table != null)
			collection_table.removeViews(0, collection_table.getChildCount());
		// Don't start messing with the collectionObj until it's free
		while (!Globals.collectionObj.getObjectState().equals("free")) {
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int current = 0; current < Globals.collectionObj.getCardList()
				.size(); current++) {
			ImageView image1 = new ImageView(this);
			image1.setImageBitmap(Globals.collectionObj.getCardList()
					.get(current).getBitmap());
			image1.setId(current);
			image1.setAdjustViewBounds(true);
			image1.setPadding(2, 2, 2, 2);
			image1.setScaleType(ScaleType.CENTER_INSIDE);
			String function = Globals.collectionObj.getCardList().get(current)
					.getType();
			if (function.equals("Artist")) {
				image1.setBackgroundColor(Color.RED);
			} else if (function.equals("Athlete")) {
				image1.setBackgroundColor(Color.YELLOW);
			} else if (function.equals("Leader")) {
				image1.setBackgroundColor(Color.BLUE);
			} else if (function.equals("Student")) {
				image1.setBackgroundColor(Color.GREEN);
			} else {
				image1.setBackgroundColor(Color.rgb(128, 0, 128));
			}
			image1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					cardSound.start();
					Card cardObj = new Card();
					cardFocus = v.getId();
					cardObj = Globals.collectionObj.getCardList()
							.get(v.getId());
					display.setImageBitmap(cardObj.getBitmap());
					String function = cardObj.getType();
					if (function.equals("Artist")) {
						display.setBackgroundColor(Color.RED);
					} else if (function.equals("Athlete")) {
						display.setBackgroundColor(Color.YELLOW);
					} else if (function.equals("Leader")) {
						display.setBackgroundColor(Color.BLUE);
					} else if (function.equals("Student")) {
						display.setBackgroundColor(Color.GREEN);
					} else {
						display.setBackgroundColor(Color.rgb(128, 0, 128));
					}
					uniqueID.setText(cardObj.getUniqueID());
					cardName.setText(cardObj.getCardName());
					type.setText(cardObj.getType());
					cost1.setText(cardObj.getCost());
					mind1.setText(cardObj.getMind1());
					charm1.setText(cardObj.getCharm1());
					strength1.setText(cardObj.getStrength1());
					special.setText(cardObj.getSpecial());
					levelUp.setText(cardObj.getLevelUp());
					wiki.setText(cardObj.getWiki());
					Linkify.addLinks(wiki, Linkify.ALL);
				}
			});
			collection_table.setHorizontalFadingEdgeEnabled(true);
			collection_table.setVerticalFadingEdgeEnabled(true);
			collection_table.setFadingEdgeLength(100);
			collection_table.addView(image1, layoutParams);
			while (!Globals.user.getObjectState().equals("free")) {
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			tokens.setText("" + Globals.user.getTokens());
		}
	}

	void fillLibraryTable() {

		for (int current = 0; current < Globals.libraryObj.getCardList().size(); current++) {
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT);
			layoutParams.setMargins(5, 0, 5, 0);
			ImageView image1 = new ImageView(this);
			// Don't start messing with the libraryObj until it is free
			while (!Globals.libraryObj.getObjectState().equals("free")) {
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			image1.setImageBitmap(Globals.libraryObj.getCardList().get(current)
					.getBitmap());
			image1.setId(current);
			image1.setAdjustViewBounds(true);
			image1.setPadding(2, 2, 2, 2);
			image1.setScaleType(ScaleType.CENTER_INSIDE);
			String function = Globals.libraryObj.getCardList().get(current)
					.getType();
			if (function.equals("Artist")) {
				image1.setBackgroundColor(Color.RED);
			} else if (function.equals("Athlete")) {
				image1.setBackgroundColor(Color.YELLOW);
			} else if (function.equals("Leader")) {
				image1.setBackgroundColor(Color.BLUE);
			} else if (function.equals("Student")) {
				image1.setBackgroundColor(Color.GREEN);
			} else {
				image1.setBackgroundColor(Color.rgb(128, 0, 128));
			}
			image1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					cardSound.start();
					Card cardObj = new Card();
					cardFocus = v.getId();
					cardObj = Globals.libraryObj.getCardList().get(v.getId());
					display.setImageBitmap(cardObj.getBitmap());
					String function = cardObj.getType();
					if (function.equals("Artist")) {
						display.setBackgroundColor(Color.RED);
					} else if (function.equals("Athlete")) {
						display.setBackgroundColor(Color.YELLOW);
					} else if (function.equals("Leader")) {
						display.setBackgroundColor(Color.BLUE);
					} else if (function.equals("Student")) {
						display.setBackgroundColor(Color.GREEN);
					} else {
						display.setBackgroundColor(Color.rgb(128, 0, 128));
					}
					uniqueID.setText("");
					cardName.setText(cardObj.getCardName());
					type.setText(cardObj.getType());
					cost1.setText(cardObj.getCost());
					mind1.setText(cardObj.getMind1());
					charm1.setText(cardObj.getCharm1());
					strength1.setText(cardObj.getStrength1());
					special.setText(cardObj.getSpecial());
					levelUp.setText(cardObj.getLevelUp());
					wiki.setText(cardObj.getWiki());
					Linkify.addLinks(wiki, Linkify.ALL);
				}
			});
			library_table.setHorizontalFadingEdgeEnabled(true);
			library_table.setVerticalFadingEdgeEnabled(true);
			library_table.setFadingEdgeLength(100);
			library_table.addView(image1, layoutParams);
		}
	}

	public class Purchasing extends AsyncTask<Context, Void, Context> {
		ProgressDialog dialog;

		@Override
		protected Context doInBackground(Context... Contexts) {
			if (Globals.user.getTokens() > 0) {
				Random randomGenerator = new Random(new Date().getTime());
				int index = randomGenerator.nextInt(Globals.libraryObj
						.getCardList().size());
				Globals.collectionObj.setCardID(Globals.libraryObj
						.getCardList().get(index).getCardID());
				Globals.collectionObj.setUserID(Globals.user.userID);
				try {

					Globals.collectionObj.sqlAddCard();
					while (!Globals.collectionObj.getObjectState().equals(
							"free")) {
						Thread.sleep(50);
					}
					Globals.user.setTokens(Globals.user.getTokens() - 1);

					Globals.collectionObj.sqlGetCollection();
					while (!Globals.collectionObj.getObjectState().equals(
							"free")) {
						Thread.sleep(50);
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

				try {
					Globals.user.sqlSetUser();
				} catch (Exception e) {
					e.printStackTrace();
				}

			} else {
				Toast.makeText(getApplicationContext(), "You have no tokens.",
						Toast.LENGTH_LONG).show();
			}
			return Contexts[0];
		}

		@Override
		protected void onPostExecute(Context result) {
			dialog.dismiss();
			fillCollectionTable();
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(CardShop.this, "", "Purchasing", true);
			dialog.show();
			super.onPreExecute();
		}
	}

	public void displayhelp() {

		HelpDialog helpDialog = new HelpDialog(CardShop.this);
		helpDialog.setTitle("Help contents");
		helpDialog.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.ingamemenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit:
			RestClient Connect = new RestClient();
			
			final MediaPlayer buttonSound = MediaPlayer.create(CardShop.this,
					R.raw.button_click);
			buttonSound.start();
			String logout = "http://emath-project.appspot.com/emath/emathservicehttp?function=logout&userID="
					+ Username.getUser();
			Connect.connect(logout);
			if (Globals.isconnected== 0){
				Toast.makeText(CardShop.this, "Connection Error", Toast.LENGTH_LONG).show();
				Globals.isconnected=1;
			}
			else{
			Connect.clear();
			finish();
			return true;
			}
		case R.id.help:
			displayhelp();
			return true;
		}
		return super.onOptionsItemSelected(item);

	}

	@Override
	protected void onPostResume() {
		if (Globals.focusedActivity.equals("CardShop")) {
			if (Globals.settingsHolder[1] == 1) {
				startService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = true;
		}
		super.onPostResume();
	}

	@Override
	protected void onPause() {
		if (this.isFinishing()) {
			Globals.focusedActivity = "GameMenu";
		} else {
			if (Globals.settingsHolder[1] == 1) {
				stopService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = false;
		}
		super.onPause();
	}
}